import axios from 'axios'
import qs from 'qs'
import { SERVER_URL, TOKEN_NAME, RES_AUTH, RES_ERROR, RES_OK } from '../app.config'
import * as Toast from '../toast'
import store from '../store'
const instance = axios.create({
  baseURL: SERVER_URL,
  timeout: 50000,
  transformRequest: function (data, headers) {
    if (data && data.json) {
      headers['Content-Type'] = 'application/json; charset=UTF-8'
      return JSON.stringify(data)
    }
    return qs.stringify(data, { arrayFormat: 'repeat' })
  }
})

// 请求前接口
instance.interceptors.request.use(function (config) {
  // 如果POST需要显示Loading
  if (config.method === 'post' && config.data && config.data.Loading) {
    Toast.showLoading()
  }
  // 设置头部
  const token = store.state.user.token
  const tokenName = TOKEN_NAME
  if (token) {
    config.headers[tokenName] = token
  }
  // Do something before request is sent
  return config
}, function (error) {
  // Do something with request error
  Toast.showError('请求错误!')
  return Promise.reject(error)
})

instance.interceptors.response.use(function (response) {
  // 先隐藏Loading
  Toast.hide()
  // 返回处理成功状态码
  if (response.data.code === RES_OK) {
    return response.data
    // 返回处理失败状态码
  } else if (response.data.code === RES_ERROR) {
    Toast.showError('失败:' + response.data.msg)
    return Promise.reject(new Error(response.msg))
  } else if (response.data.code === RES_AUTH) {
    Toast.showError('登录过期:重新进入' + response.data.msg)
    return Promise.reject(new Error('请先登录!'))
  } else {
    Toast.showError('未知业务错误,联系管理员!')
    return Promise.reject(new Error('未知业务错误,联系管理员!' + response.data.code))
  }
}, function (error) {
  Toast.showError('手机网络状态不佳')
  return Promise.reject(error)
})

export default instance
